package main

import (
	"fmt"
	"time"
)
/**
实现一个最简单的线程池，n个线程打印m个数字
 */
func main()  {
	workPool(10, 50)
	fmt.Printf("all done\n")
}

func work(i int, jobs <-chan int, jobDone chan<- int) {
	for j := range jobs {
		time.Sleep(time.Second)
		fmt.Println("work ", i, " do job ", j)
		jobDone<-1
	}
}

func workPool(workNum int, jobNums int) {
	//定义channel
	jobs := make(chan int)
	jobDone := make(chan int)
	allDone := make(chan int)

	//起n个工作协程
	for i:=0; i<workNum; i++ {
		go work(i, jobs, jobDone)
	}

	//监听任务是否都已经完成
	go func(jobNums int) {
		doneNum := 0
		for range jobDone {
			doneNum++
			if doneNum == jobNums {
				allDone<-1
				return
			}
		}
	}(jobNums)

	//分配n个任务
	for i:=0; i<jobNums; i++ {
		jobs<-i
	}

	<-allDone
}